<?php

namespace App\Http\Controllers\backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;

use App\Model\backend\PerformanceAreaModel;
use App\Model\backend\PerformanceRatioModel;
use App\Model\backend\TemplatesStagesTaskModel;

class PerformanceController extends Controller
{
    function __construct(){
		
		$session = session('member');
		if($session['gid'] != 1) abort(403,'Unauthorized action.');
	}
	
	function index(){
		$area = PerformanceAreaModel::orderBy('area_start')->get();
		$task = TemplatesStagesTaskModel::orderBy('task_id')->get();
		$ratioArr = PerformanceRatioModel::get();
		$ratio = $temp = [];
		
		
		foreach($ratioArr as $r){
			$temp[$r['task_id']][$r['area_id']]['percent'] = $r['percent'];
			$temp[$r['task_id']][$r['area_id']]['ratio_id'] = $r['ratio_id'];
		}
		
		// 任务利率组合到任务数组里
		foreach($task as $k => $t){
			$rate = [];
			foreach($area as $a){
				if(isset($temp[$t['task_id']][$a['area_id']])){
					$rate[] = [
						'percent' => $temp[$t['task_id']][$a['area_id']]['percent'],
						'ratio_id' => $temp[$t['task_id']][$a['area_id']]['ratio_id'],
						'class' => $temp[$t['task_id']][$a['area_id']]['percent'] == '0.00' ? 'red':''
					];
				}else{
					$rate[] = ['percent'=>'', 'ratio_id'=>'', 'class'=>''];
				}
			}
			$task[$k]['rate'] = $rate;
		}
		
		return view('backend.performance.index', compact('area','task', 'ratio'));
	}
	
	// 添加-修改面积
	function store(Request $req){
		
		$input = $req->all();
		if($input['area_id']){
			$area = PerformanceAreaModel::findOrFail($input['area_id']);
			$area->area_start = $input['area_start'];
			$area->area_end = $input['area_end'];
			$area->save();
		}else{
			$flag = PerformanceAreaModel::create($input);

			if($flag){
				$task = TemplatesStagesTaskModel::orderBy('task_id')->get();
				foreach($task as $t){
					$ratio = new PerformanceRatioModel;
					$ratio->task_id = $t['task_id'];
					$ratio->area_id = $flag['area_id'];
					$ratio->save();
				}
			}
		}
	}
	
	function addArtio(Request $req){
		// echo $req->input('ratio_id');exit;
		$artio = PerformanceRatioModel::find($req->input('ratio_id'));
		// dd($artio);
		$artio->percent = $req->percent;
		$artio->save();
		echo 1;
	}
	
	function show(){
		echo env('DB_PREFIX', 'test');
	}
	
	function destroy($id){
		
	}
}
